const fs = require('fs');
const { exec } = require('child_process');
getM3u8()
async function getM3u8() {

    const data1 = await fetch('https://gh-proxy.com/raw.githubusercontent.com/vbskycn/iptv/refs/heads/master/tv/iptv4.m3u').then(response => response.text())
    const data2 = await fetch('https://live.hacks.tools/tv/iptv4.m3u').then(response => response.text())
    parseM3U8(data1 + data2)
}

function parseM3U8(content) {
    const lines = content.split('\n');
    let channels = [];
    let currentChannel = {};
    for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim();
        if (!line) continue;
        if (line.startsWith('#EXTINF:')) {
            // 频道信息行
            const params = line.substring(8).split(',');
            const attributes = params[0].split(' ');
            const name = params.slice(1).join(',');
            currentChannel = {
                name: name,
                group: '未分组',
                url: ''
            };

            // 解析属性
            for (let attr of attributes) {
                if (attr.includes('="')) {
                    const [key, value] = attr.split('=');
                    const cleanValue = value.replace(/"/g, '');

                    if (key === 'group-title') {
                        currentChannel.group = cleanValue;
                    }
                }
            }
        } else if (line.startsWith('http')) {
            // URL行
            currentChannel.url = line;
            channels.push(currentChannel);
            currentChannel = {};
        }
    }
    channels = channels.filter((item, index, self) =>
        index === self.findIndex(t => t.url === item.url)
    );
    filterChannels(channels)

}

async function filterChannels(channels) {
    const result = []
    for (let i = 0; i < channels.length; i++) {
        let channel = channels[i]
        if (channel.url) {
            // 检测流地址
            const isValid = await checkStream(channel.url);

            if (isValid) {
                console.log(`共${channels.length}, 第${i}个【有效】`);
                result.push(channel)
                fs.writeFileSync('index.js', `var channels = ${JSON.stringify(result)}`);
            } else {
                console.log(`共${channels.length}, 第${i}个【无效】`);
            }
        }
    }
}

// 执行ffprobe命令检测流地址
function checkStream(url) {
    return new Promise((resolve) => {
        let timeoutId;
        let timeCount = 5000;
        // 设置超时
        const process = exec(
            `ffprobe -v quiet -timeout ${timeCount * 1000} -rw_timeout ${timeCount * 1000} -show_format -show_streams "${url}"`,
            (error) => {
                clearTimeout(timeoutId);
                if (error) {
                    resolve(false); // 无效源
                } else {
                    resolve(true); // 有效源
                }
            }
        );

        // 处理超时
        timeoutId = setTimeout(() => {
            process.kill();
            resolve(false); // 超时视为无效源
        }, timeCount);
    });
}
